import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import {getAdminLoginToken, getBackLoginToken} from "@/api/login";

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  id: '',
  waitOrderNum: 0,
  cancelOrderNum: 0,
  returnOrderNum: 0,
  pickNum: 0,
  exceptGoodsNum: 0,
  shipmentTipsNum: 0,
  deliverNum: 0,
  systemTime: 0,
  siteId: 'MX',
  timeSite: 'MX',
  inventoryTipsNum: 0,
  stockTipsNum: 0,
  platformNum: 1, // 对接的平台数量
  defaultAccountTypeNum: 1, // 默认平台的选项
  accountMKD: false, // 是否对接了美客多平台
  accountFalabella: false, // 是否对接了falabella平台
  accountAmazon: false, // 是否对接了amazon平台
  faInventoryTipsNum: 0,
  accountShopee: false, // 是否授权了虾皮平台
  accountShein: false, // 是否授权了希音平台
  accountTikTok: false, // 是否授权了抖音平台
  accountAliexpress: false, // 是否授权了速卖通平台
  spInventoryTipsNum: 0, // 库存提醒数
  siInventoryTipsNum: 0, // 库存提醒数
  awsInventoryTipsNum: 0, // 库存提醒数
  tiktokInventoryTipsNum: 0, // 库存提醒数
  aliexpressInventoryTipsNum: 0, // 库存提醒数
  userAmountTipsNum: 0, // 用户金额异常数量
  warehouseName: '仓库',
  // 大货中转
  labelOrderNum: 0, // 贴标数
  middleWorkNum: 0, // 送仓工单数
  transferWorkNum: 0, // 调货工单数
  // 汇款
  waitForConfirmationRemittanceNum: 0, //待处理汇款数
  payPageType: 'SKIP', // 支付页面类型 SKIP: 跳转  POP: 弹框
  combinationNum: 0, // 组装工单数量
  warehouseId: 0,

  // 库位
  inventoryLocationNum: 0,
  localTime: '',
  // 小包商品
  packetGoodsNum: 0,
  // 小包订单
  packetOrderNum: 0,
  // 库存预警
  goodsTipsNum: 0,
  roleType: '',

  info: {},
  isShowLog:1,

}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_WAIT_ORDER_NUM: (state, waitOrderNum) => {
    state.waitOrderNum = waitOrderNum
  },
  SET_CANCEL_ORDER_NUM: (state, cancelOrderNum) => {
    state.cancelOrderNum = cancelOrderNum
  },
  SET_RETURN_ORDER_NUM: (state, returnOrderNum) => {
    state.returnOrderNum = returnOrderNum
  },
  SET_PICK_NUM: (state, pickNum) => {
    state.pickNum = pickNum
  },
  SET_EXCEPT_GOODS_NUM: (state, exceptGoodsNum) => {
    state.exceptGoodsNum = exceptGoodsNum
  },
  SET_SHIPMENT_TIPS_NUM: (state, shipmentTipsNum) => {
    state.shipmentTipsNum = shipmentTipsNum
  },
  SET_DELIVER_NUM: (state, deliverNum) => {
    state.deliverNum = deliverNum
  },
  SET_SYSTEM_TIME: (state,systemTime) => {
    state.systemTime = systemTime
  },
  SET_SITE_ID: (state,siteId) => {
    state.siteId = siteId
  },
  SET_TIME_SITE: (state,timeSite) => {
    state.timeSite = timeSite
  },
  SET_INVENTORY_TIPS: (state,inventoryTipsNum) => {
    state.inventoryTipsNum = inventoryTipsNum
  },
  SET_FA_INVENTORY_TIPS: (state,faInventoryTipsNum) => {
    state.faInventoryTipsNum = faInventoryTipsNum
  },
  SET_SP_INVENTORY_TIPS: (state,spInventoryTipsNum) => {
    state.spInventoryTipsNum = spInventoryTipsNum
  },
  SET_SI_INVENTORY_TIPS: (state,siInventoryTipsNum) => {
    state.siInventoryTipsNum = siInventoryTipsNum
  },
  SET_AWS_INVENTORY_TIPS: (state,awsInventoryTipsNum) => {
    state.awsInventoryTipsNum = awsInventoryTipsNum
  },
  SET_TIKTOK_INVENTORY_TIPS: (state,tiktokInventoryTipsNum) => {
    state.tiktokInventoryTipsNum = tiktokInventoryTipsNum
  },
  SET_ALIEXPRESS_INVENTORY_TIPS: (state,aliexpressInventoryTipsNum) => {
    state.aliexpressInventoryTipsNum = aliexpressInventoryTipsNum
  },
  SET_STOCK_TIPS: (state,stockTipsNum) => {
    state.stockTipsNum = stockTipsNum
  },
  SET_PLAT_NUM: (state,platformNum) => {
    state.platformNum = platformNum
  },
  SET_DEFAULT_ACCOUNT_TYPE_NUM: (state,defaultAccountTypeNum)=>{
    state.defaultAccountTypeNum = defaultAccountTypeNum
  },
  SET_ACCOUNT_MKD: (state,accountMKD)=>{
    state.accountMKD = accountMKD
  },
  SET_ACCOUNT_FALABELLA: (state,accountFalabella)=>{
    state.accountFalabella = accountFalabella
  },
  SET_ACCOUNT_AMAZON: (state,accountAmazon)=>{
    state.accountAmazon = accountAmazon
  },
  SET_ACCOUNT_SHOPEE: (state,accountShopee)=>{
    state.accountShopee = accountShopee
  },
  SET_ACCOUNT_SHEIN: (state,accountShein)=>{
    state.accountShein = accountShein
  },
  SET_ACCOUNT_TIKTOK: (state,accountTikTok)=>{
    state.accountTikTok = accountTikTok
  },
  SET_ACCOUNT_ALIEXPRESS: (state,accountAliexpress)=>{
    state.accountAliexpress = accountAliexpress
  },
  SET_USER_AMOUNT_TIPS:(state,userAmountTipsNum)=>{
    state.userAmountTipsNum = userAmountTipsNum
  },
  SET_WAREHOUSE_NAME: (state,warehouseName) =>{
    state.warehouseName = warehouseName
  },
  SET_LABEL_ORDER_NUM: (state,labelOrderNum) =>{
    state.labelOrderNum = labelOrderNum
  },
  SET_MIDDLE_WORK_NUM: (state,middleWorkNum) =>{
    state.middleWorkNum = middleWorkNum
  },
  SET_TRANSFER_WORK_NUM: (state,transferWorkNum) =>{
    state.transferWorkNum = transferWorkNum
  },
  SET_WAIT_FOR_CONFIRMATION_REMITTANCE_NUM: (state, waitForConfirmationRemittanceNum) => {
    state.waitForConfirmationRemittanceNum = waitForConfirmationRemittanceNum
  },
  SET_PAY_PAGE_TYPE: (state,payPageType) =>{
    state.payPageType = payPageType
  },
  // 设置导航栏数字
  SET_NAVBAR_NUM: (state,navbarNum) =>{
    state.combinationNum = navbarNum.combinationNum || 0
  },
  SET_INFO: (state, info)=>{
    state.warehouseId = info.warehouseId
    state.localTime = info.localTime
    state.roleType = info.roleType
    state.info = info
  },
  SET_INVENTORY_LOCATION_NUM: (state,inventoryLocationNum) =>{
    state.inventoryLocationNum = inventoryLocationNum
  },
  SET_PACKET_GOODS_NUM: (state,packetGoodsNum) =>{
    state.packetGoodsNum = packetGoodsNum
  },
  SET_IS_SHOW_LOG: (state, isShowLog) => {
    state.isShowLog = isShowLog
  },
  SET_PACKET_ORDER_NUM: (state,packetOrderNum) =>{
    state.packetOrderNum = packetOrderNum
  },
  SET_GOODS_TIPS_NUM: (state, goodsTipsNum) => {
    state.goodsTipsNum = goodsTipsNum
  },
}


const actions = {
  // user login
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        const { data, info } = res
        if(res.error === 0){
          commit('SET_TOKEN', info.token)
          setToken(info.token)
          resolve()
        }else{
          reject(res)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(res => {
        const { data, info } = res
        if (!data.id) {
          reject('Verification failed, please Login again.')
        }

        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        /*if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }*/

        // const roles = [data.accountType];
        // 用户角色
        const roles = data.roles;
        const name = data.account;
        const avatar = data.avatar;
        const introduction = '';

        commit('SET_ID', data.id)
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)

        commit('SET_WAIT_ORDER_NUM', info.waitOrderNum)
        commit('SET_CANCEL_ORDER_NUM', info.cancelOrderNum)
        commit('SET_RETURN_ORDER_NUM', info.returnOrderNum)
        commit('SET_PICK_NUM', info.pickNum)
        commit('SET_EXCEPT_GOODS_NUM', info.exceptGoodsNum)
        commit('SET_SHIPMENT_TIPS_NUM', info.shipmentTipsNum)
        commit('SET_DELIVER_NUM', info.deliverNum)

        commit('SET_SYSTEM_TIME', new Date(info.localTime).getTime())

        commit('SET_SITE_ID', data.siteId)
        commit('SET_TIME_SITE', info.timeSite)

        commit('SET_INVENTORY_TIPS', info.inventoryTipsNum)
        commit('SET_FA_INVENTORY_TIPS', info.faInventoryTipsNum)
        commit('SET_SP_INVENTORY_TIPS', info.spInventoryTipsNum)
        commit('SET_SI_INVENTORY_TIPS', info.siInventoryTipsNum)
        commit('SET_AWS_INVENTORY_TIPS', info.awsInventoryTipsNum)
        commit('SET_TIKTOK_INVENTORY_TIPS', info.tiktokInventoryTipsNum)
        commit('SET_ALIEXPRESS_INVENTORY_TIPS', info.aliexpressInventoryTipsNum)
        commit('SET_STOCK_TIPS', info.stockTipsNum)
        commit('SET_PLAT_NUM', info.platformNum)
        commit('SET_ACCOUNT_MKD', info.accountMKD > 0)
        commit('SET_ACCOUNT_FALABELLA', info.accountFalabella > 0)
        commit('SET_ACCOUNT_AMAZON', info.accountAmazon > 0)
        commit('SET_ACCOUNT_SHOPEE', info.accountShopee > 0)
        commit('SET_ACCOUNT_SHEIN', info.accountShein > 0)
        commit('SET_ACCOUNT_TIKTOK', info.accountTikTok > 0)
        commit('SET_ACCOUNT_ALIEXPRESS', info.accountAliexpress > 0)
        commit('SET_IS_SHOW_LOG', info.isShowLog)

        let defaultAccountTypeNum = 1;
        if(info.accountMKD >= 1){
          defaultAccountTypeNum = 1;
        }else if(info.accountFalabella >= 1){
          defaultAccountTypeNum = 2;
        }else if(info.accountShopee >= 1){
          defaultAccountTypeNum = 3;
        }else if(info.accountShein >= 1){
          defaultAccountTypeNum = 4;
        }else if(info.accountAmazon >= 1){
          defaultAccountTypeNum = 5;
        }else if(info.accountTikTok >= 1){
          defaultAccountTypeNum = 6;
        }else if(info.accountAliexpress >= 1){
          defaultAccountTypeNum = 8;
        }
        commit('SET_DEFAULT_ACCOUNT_TYPE_NUM', defaultAccountTypeNum)

        commit('SET_USER_AMOUNT_TIPS',info.userAmountTipsNum)

        commit('SET_WAREHOUSE_NAME',info.warehouseName);

        // 大货中转
        commit('SET_LABEL_ORDER_NUM',info.labelOrderNum);
        commit('SET_MIDDLE_WORK_NUM',info.middleWorkNum);
        commit('SET_TRANSFER_WORK_NUM',info.transferWorkNum);

        commit('SET_WAIT_FOR_CONFIRMATION_REMITTANCE_NUM', info.waitForConfirmationRemittanceNum)
        commit('SET_PAY_PAGE_TYPE',info.payPageType)
        commit('SET_PACKET_GOODS_NUM',info.packetGoodsNum)
        commit('SET_PACKET_ORDER_NUM',info.packetOrderNum)
        commit('SET_INVENTORY_LOCATION_NUM',info.inventoryLocationNum)
        commit('SET_GOODS_TIPS_NUM', info.goodsTipsNum)

        // 设置导航栏的数字
        const navbarNum = {
          combinationNum: info.combinationNum
        }
        commit('SET_NAVBAR_NUM',navbarNum);

        commit('SET_INFO',info);

        resolve({ roles, name, avatar, introduction })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },


  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // 后台登录
  adminLogin({ commit } ,key){
    return new Promise((resolve, reject) =>{
      getAdminLoginToken(key)
        .then( res => {
          const { info } = res
          if(res.error === 0){
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resetRouter()
            commit('SET_TOKEN', info.token)
            setToken(info.token)
            resolve()
          }else{
            reject(res)
          }
        }).catch( error => {
          reject(error)
        })
    })
  },

  // 更改时间
  setSystemTime({commit},time){
    commit('SET_SYSTEM_TIME',time)
  },

  // 演示登录
  backLogin({commit},key){
    return new Promise((resolve, reject) =>{
      getBackLoginToken(key)
        .then( res => {
          const { info } = res
          if(res.error === 0){
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resetRouter()
            commit('SET_TOKEN', info.token)
            setToken(info.token)
            resolve()
          }else{
            reject(res)
          }
        }).catch( error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
